package com.prawn.authority.controller;

import java.io.IOException;
import java.util.*;

import com.netflix.discovery.converters.Auto;
import com.prawn.authority.client.traceabilityClient;
import com.prawn.authority.pojo.*;
import com.prawn.authority.service.*;
import com.prawn.authority.utils.FastDFSUtil;
import com.prawn.authority.utils.GlobalException;
import com.prawn.authority.utils.ResponseUtil;
import com.prawn.authority.utils.SecurityContextUtil;
import entity.Base;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.web.multipart.MultipartFile;
import util.IdWorker;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 控制器层
 *
 * @author Administrator
 */
@Api(tags = "管理管理员相关接口", description = "提供管理管理员相关的 Rest API")
@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {


    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private FunctionService functionService;

    @Autowired
    private FastDFSUtil fastDFSUtil;

    @Value("${fdfs.web-server-url}")
    private String fastdfsUrl;

    //默认头像
    @Value("${defaultPhotoUrl}")
    private String defaultPhotoUrl;

    @Autowired
    private CaptchaService captchaService;

    @Auto
    private EmailService emailService;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private traceabilityClient traceabilityClient;

    /**
     * 登陆
     *
     * @return
     */
    @ApiOperation("登陆接口")
    @ApiImplicitParam(paramType = "body", name = "user", value = "{\n" +
            "  \"loginId\": 123456,\n" +
            "  \"password\": 123456\n" +
            "}", required = true, dataType = "User")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(@RequestBody User user,
                        @RequestParam("captcha") String captcha,
                        HttpServletRequest request,
                        HttpServletResponse response) {

        if (!captchaService.checkVerificationCode(request, captcha)) {
            return new Result(false, StatusCode.LOGINERROR, "验证码错误");
        }

        User userLogin = userService.login(user);
        UserDetailsImpl userDetailsImpl = (UserDetailsImpl) userLogin;

        if (userLogin.getIsAdmin() == 0) {
            return new Result(false, StatusCode.LOGINERROR, "登陆失败");
        }

        String photo = userService.getPhoto(userLogin.getUserId());
        if (photo == null || "".equals(photo)) {
            photo = defaultPhotoUrl;
        }

        // 返回给前端的map
        Map<String, Object> map = new HashMap<>();
        map.put("loginId", userLogin.getLoginId());
        map.put("userName", userLogin.getName());
        map.put("photo", photo);
        // 返回管理员可见模块
        map.put("menuList", functionService.grand(functionService.findByUserId(userDetailsImpl.getUserId())));
        map.put("role", "manager");
        map.put("userId", userDetailsImpl.getUserId());
        map.put("baseId", userDetailsImpl.getBaseId());
        map.put("baseIdentity", userDetailsImpl.getBaseIdentity());
        map.put("merchantId", userDetailsImpl.getMerchantId());

        // 获取jwt来返回给前端
        String token = jwtUtil.createJWT(
                userDetailsImpl.getUserId(),
                userDetailsImpl.getUsername(),
                "manager");


        // 把token写入响应体中
        ResponseUtil.placeToken(response,token);

        return new Result(true, StatusCode.OK, "登陆成功", map);
    }


    /**
     * 查询全部管理员数据
     *
     * @return
     */
    @ApiOperation("查询全部管理员接口")
    @PreAuthorize("hasAnyAuthority('authority')")
    @RequestMapping(value = "/admin", method = RequestMethod.GET)
    public Result findAllAdmin() {
        return new Result(true, StatusCode.OK, "查询成功", userService.findAllAdmin());
    }


    /**
     * 根据ID查询管理员
     *
     * @param id ID
     * @return
     */
    @ApiImplicitParam(paramType = "path", name = "id", value = "userID", required = true, dataType = "String")
    @ApiOperation("根据id查询管理员接口")
    @PreAuthorize("hasAnyAuthority('authority')")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findAdminByUserId(id));
    }


    /**
     * 增加管理员
     *
     * @param user
     */
    @ApiOperation("新增管理员接口")
    @ApiImplicitParam(paramType = "body", name = "user", value = "{\n" +
            "  \"*email\": \"1234@163.com\",\n" +
            "  \"*loginId\": \"123456\",\n" +
            "  \"mobile\": \"13513513513\",\n" +
            "  \"name\": \"张三\",\n" +
            "  \"*password\": \"123456\",\n" +
            "  \"phone\": \"123456789\",\n" +
            "  \"sex\": \"男\"\n" +
            "}", required = true, dataType = "User")
    @PreAuthorize("hasAnyAuthority('authority_admin_add')")
    @RequestMapping(method = RequestMethod.POST)
    public Result add(@RequestBody User user) {
        user.setIsAdmin(1);
        userService.add(user);
        User userByLoginId = userService.findByLoginId(user.getLoginId());
        userService.uploadPhoto(userByLoginId.getUserId(), null);
        return new Result(true, StatusCode.OK, "增加成功");
    }


    /**
     * 删除
     *
     * @param id
     */
    @ApiOperation("删除管理员接口")
    @ApiImplicitParam(paramType = "path", name = "id", value = "管理员ID", required = true, dataType = "String")
    @PreAuthorize("hasAnyAuthority('authority_admin_delete')")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id) {
        try {
            int begin = fastdfsUrl.length() + 8 - 1;
            String photo = userService.getPhoto(id);
            String deleteUrl = photo.substring(begin);
            fastDFSUtil.deleteFile(deleteUrl);
        } catch (NullPointerException e) {
        }
        userService.delUserAndPhoto(id);
        userService.deleteUserById(id, 1);
        return new Result(true, StatusCode.OK, "删除成功");
    }

    /**
     * 查询可添加的角色
     */
    @ApiOperation("查询可给该管理员添加的角色")
    @ApiImplicitParam(paramType = "path", name = "userId", value = "管理员ID", required = true, dataType = "String")
    @PreAuthorize("hasAnyAuthority('authority_admin')")
    @RequestMapping(value = "/otherRole/{userId}", method = RequestMethod.GET)
    public Result findOthers(@PathVariable String userId) {
        return new Result(true, StatusCode.OK, "查找角色成功", roleService.findOthersByUserId(userId));
    }

    /**
     * 查询已拥有的角色
     */
    @ApiOperation("查询该管理员已拥有的角色")
    @ApiImplicitParam(paramType = "path", name = "userId", value = "管理员ID", required = true, dataType = "String")
    @PreAuthorize("hasAnyAuthority('authority_admin')")
    @RequestMapping(value = "/role/{userId}", method = RequestMethod.GET)
    public Result findRoles(@PathVariable String userId) {
        return new Result(true, StatusCode.OK, "查找角色成功", roleService.findRoleByUserId(userId));
    }

    /**
     * 查询已拥有的权限
     */
    @ApiOperation("查询该管理员已拥有的权限")
    @RequestMapping(value = "/authority", method = RequestMethod.GET)
    public Result findAuthority() {
        UserDetailsImpl user = SecurityContextUtil.getUserDetails();

        return new Result(true, StatusCode.OK, "查找权限成功", functionService.grand(functionService.findByUserId(user.getUserId())));
    }

    /**
     * 查询在某一模块中已拥有的权限
     */
    @ApiOperation("查询在某一模块中已拥有的权限")
    @RequestMapping(value = "/authority/{module}", method = RequestMethod.GET)
    public Result findAuthorityBy(@PathVariable String module) {
        UserDetailsImpl user = SecurityContextUtil.getUserDetails();
        List<FunctionParent> functionList = functionService.grand(functionService.findByUserId(user.getUserId()));
        List<FunctionParent> functionListInModule = new ArrayList<>();

        // 将不符合的去掉
        for(FunctionParent function: functionList){
            if(function.getName().startsWith(module)){
                functionListInModule.add(function);
            }
        }

        return new Result(true, StatusCode.OK, "查找权限成功", functionListInModule);
    }


    /**
     * 更新管理员角色
     *
     * @param userId
     * @param roleIdList
     * @return
     */
    @ApiOperation("超级管理员更新管理员角色接口")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "userId", value = "管理员ID", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "body", name = "roleIdList", value = "{\"roleIdList\": [\"roleId1\", \"roleId2\"]}", dataType = "Map")
    })
    @PreAuthorize("hasAnyAuthority('authority_admin_updateRole')")
    @RequestMapping(value = "/{userId}", method = RequestMethod.POST)
    public Result updateRoleOfUser(@PathVariable String userId, @RequestBody Map roleIdList) {
        userService.UpdateRoleOfAdmin(userId, roleIdList);
        return new Result(true, StatusCode.OK, "更新管理员角色成功");
    }


    /**
     * 超级管理员修改普通管理员
     *
     * @param user
     * @param id
     * @return
     */

    @ApiOperation("修改普通管理员基本信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "管理员ID", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "body", name = "user", value = "{\n" +
                    "  \"email\": \"1234@163.com\",\n" +
                    "  \"loginId\": \"123456\",\n" +
                    "  \"mobile\": \"13513513513\",\n" +
                    "  \"name\": \"张三\",\n" +
                    "  \"password\": \"123456\",\n" +
                    "  \"phone\": \"123456789\",\n" +
                    "  \"sex\": \"男\"\n" +
                    "}", required = true, dataType = "User")
    })
    @PreAuthorize("hasAnyAuthority('authority_admin_update')")
    @RequestMapping(value = "/admin/{id}", method = RequestMethod.PUT)
    public Result updateUser(@RequestBody User user, @PathVariable String id) {
        user.setUserId(id);
        user.setIsAdmin(1);
        userService.updateUser(user, 1);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @ApiOperation("条件查询接口")
    @ApiImplicitParam(paramType = "body", name = "searchMap", value = "{\n" +
            "\t\t\"baseId\": \"123456\",\n" +
            "\t\t\t\t\"baseIdentity\": 1,\n" +
            "\t\t\t\t\"email\": \"123@163.com\",\n" +
            "\t\t\t\t\"loginId\": \"123456\",\n" +
            "\t\t\t\t\"merchantId\": \"123456\",\n" +
            "\t\t\t\t\"mobile\": \"13513513513\",\n" +
            "\t\t\t\t\"name\": \"张三\",\n" +
            "\t\t\t\t\"phone\": \"12345678\",\n" +
            "\t\t\t\t\"sex\": \"男\"\n" +
            "\t}", required = true, dataType = "User")
    @PreAuthorize("hasAnyAuthority('authority_admin')")
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findSearchUser(searchMap, "1"));
    }

    /**
     * 分页+多条件查询管理员
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @ApiOperation("分页加条件查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "page", value = "页面", dataType = "Integer"),
            @ApiImplicitParam(paramType = "path", name = "size", value = "尺寸", dataType = "Integer"),
            @ApiImplicitParam(paramType = "body", name = "searchMap", value = "{\n" +
                    "\t\t\"baseId\": \"123456\",\n" +
                    "\t\t\t\t\"baseIdentity\": 1,\n" +
                    "\t\t\t\t\"email\": \"123@163.com\",\n" +
                    "\t\t\t\t\"loginId\": \"123456\",\n" +
                    "\t\t\t\t\"merchantId\": \"123456\",\n" +
                    "\t\t\t\t\"mobile\": \"13513513513\",\n" +
                    "\t\t\t\t\"name\": \"张三\",\n" +
                    "\t\t\t\t\"phone\": \"12345678\",\n" +
                    "\t\t\t\t\"sex\": \"男\"\n" +
                    "\t}", required = true, dataType = "User")
    })
    @PreAuthorize("hasAnyAuthority('authority_admin')")
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<User> pageList = userService.findSearchUser(searchMap, page, size, "1");
        return new Result(true, StatusCode.OK, "查询成功", new PageResult<User>(pageList.getTotalElements(), pageList.getContent()));
    }


    /**
     * 更新基地管理员
     *
     * @param userId
     * @param baseId
     * @return
     */
    @ApiOperation("更新基地管理员接口")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "userId", value = "用户id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "path", name = "baseId", value = "基地id", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "path", name = "baseIdentity", value = "权限", dataType = "Integer")
    })
    @PreAuthorize("hasAnyAuthority('authority')")
    @RequestMapping(value = "/update/{userId}/{baseId}/{baseIdentity}", method = RequestMethod.PUT)
    public Result updateBaseAdmin(@PathVariable String userId, @PathVariable String baseId, @PathVariable int baseIdentity) {
        userService.updateBaseAdmin(userId, baseId, baseIdentity);

        Map message = (Map)redisTemplate.opsForValue().get("baseMessage");
        message.remove(userId);
        redisTemplate.opsForValue().set("baseMessage", message);

        return new Result(true, StatusCode.OK, "更新成功");
    }

    /**
     * 拒绝更新基地管理员接口
     * @param userId
     * @return
     */
    @ApiOperation("拒绝更新基地管理员接口")
    @ApiImplicitParam(paramType = "path", name = "userId", value = "用户id", required = true, dataType = "String")
    @PreAuthorize("hasAnyAuthority('authority')")
    @RequestMapping(value = "/rejectUpdate/{userId}", method = RequestMethod.PUT)
    public Result rejectUpdateBaseAdmin(@PathVariable String userId){
        Map message = (Map)redisTemplate.opsForValue().get("baseMessage");
        message.remove(userId);
        redisTemplate.opsForValue().set("baseMessage", message);

        return new Result(true, StatusCode.OK, "拒绝成功");
    }

    /**
     * 管理员获取当前申请成为基地管理员的信息
     *
     * @return
     */
    @ApiOperation("获取当前申请成为基地管理员的信息")
    @PreAuthorize("hasAnyAuthority('authority')")
    @RequestMapping(value = "/message/detail", method = RequestMethod.GET)
    public Result findMessage(){
        Map message = (Map)redisTemplate.opsForValue().get("baseMessage");
        return new Result(true, StatusCode.OK, "查询成功", message);
    }

    /**
     * 管理员获取当前申请成为基地管理员的数量
     *
     * @return
     */
    @ApiOperation("获取当前申请成为基地管理员的数量")
    @PreAuthorize("hasAnyAuthority('authority')")
    @RequestMapping(value = "/message/number", method = RequestMethod.GET)
    public Result findMessageNum(){
        Map message = (Map)redisTemplate.opsForValue().get("baseMessage");
        return new Result(true, StatusCode.OK, "查询成功", message == null ? 0 : message.size());
    }

    /**
     * 同意新增基地
     *
     * @param userId
     * @param
     * @return
     */
    @ApiOperation("同意新增基地员接口")
    @ApiImplicitParam(paramType = "path", name = "userId", value = "用户id", required = true, dataType = "String")
    @PreAuthorize("hasAnyAuthority('authority')")
    @RequestMapping(value = "/addBase/{userId}", method = RequestMethod.POST)
    public Result updateBaseAdmin(@PathVariable String userId) {
        Map message = (Map)redisTemplate.opsForValue().get("addBaseMessage");
        if (message != null && !"".equals(message)){
            Base base = (Base) message.get(userId);
            userService.setBase(userId, base.getId(),2);
            message.remove(userId);
            redisTemplate.opsForValue().set("addBaseMessage", message);
            return traceabilityClient.addBase(base);
        }
        return new Result(false, StatusCode.ERROR, "新增失败");
    }

    /**
     * 拒绝用户新建基地接口
     * @param userId
     * @return
     */
    @ApiOperation("拒绝用户新建基地接口")
    @ApiImplicitParam(paramType = "path", name = "userId", value = "用户id", required = true, dataType = "String")
    @PreAuthorize("hasAnyAuthority('authority')")
    @RequestMapping(value = "/addBase/reject/{userId}", method = RequestMethod.PUT)
    public Result rejectAddBase(@PathVariable String userId){
        Map message = (Map)redisTemplate.opsForValue().get("addBaseMessage");
        message.remove(userId);
        redisTemplate.opsForValue().set("addBaseMessage", message);

        return new Result(true, StatusCode.OK, "拒绝成功");
    }

    /**
     * 管理员获取当前申请新建基地员的信息
     *
     * @return
     */
    @ApiOperation("获取当前申请新建基地的信息")
    @PreAuthorize("hasAnyAuthority('authority')")
    @RequestMapping(value = "/addBase/detail", method = RequestMethod.GET)
    public Result findAddBaseMessage(){
        Map message = (Map)redisTemplate.opsForValue().get("addBaseMessage");
        return new Result(true, StatusCode.OK, "查询成功", message);
    }

    /**
     * 管理员获取当前申请新建地员的数量
     *
     * @return
     */
    @ApiOperation("获取当前申请新建基地的数量")
    @PreAuthorize("hasAnyAuthority('authority')")
    @RequestMapping(value = "/addBase/number", method = RequestMethod.GET)
    public Result findAddBaseMessageNum(){
        Map message = (Map)redisTemplate.opsForValue().get("addBaseMessage");
        return new Result(true, StatusCode.OK, "查询成功", message == null ? 0 : message.size());
    }

    /**
     * 管理员查看自己信息接口
     */
    @ApiOperation("管理员查询自己信息接口")
    @RequestMapping(value = "/self", method = RequestMethod.GET)
    public Result findSelf() {
        UserDetailsImpl user = SecurityContextUtil.getUserDetails();
        return new Result(true, StatusCode.OK, "查询成功", userService.findAdminByUserId(user.getUserId()));
    }

    /**
     * 获取头像
     */
    @ApiOperation(value = "管理员获取头像")

    @RequestMapping(value = "/getPhoto/{userId}", method = RequestMethod.GET)
    public Result getPhoto(@PathVariable String userId) {
        String photo = userService.getPhoto(userId);
        if (photo == null || "".equals(photo)) {
            photo = defaultPhotoUrl;
        }
        return new Result(true, StatusCode.OK, "查询头像成功", photo);
    }

    /**
     * 更换头像
     *
     * @param file
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "更换头像")
    @RequestMapping(value = "/updatePhoto/{userId}", method = RequestMethod.POST)
    public Result updatePhoto(@PathVariable String userId, @RequestParam("file") MultipartFile file) throws IOException {
        try {
            String photo = userService.getPhoto(userId);
            if (photo == null || "".equals(photo)) {
            } else {
                int begin = fastdfsUrl.length() + 8 - 1;
                String deleteUrl = photo.substring(begin);
                fastDFSUtil.deleteFile(deleteUrl);
            }

        } catch (NullPointerException e) {
        }
        String url = fastDFSUtil.uploadFile(file);
        userService.updatePhoto(userId, url);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    /**
     * 删除头像
     *
     * @param
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "删除头像")
    @RequestMapping(value = "/deletePhoto/{userId}", method = RequestMethod.DELETE)
    public Result deletePhoto(@PathVariable String userId) {
        try {
            int begin = fastdfsUrl.length() + 8 - 1;
            String photo = userService.getPhoto(userId);
            if(photo == null || "".equals(photo)){
                return new Result(false, StatusCode.ERROR, "默认头像不能删除");
            }
            String deleteUrl = photo.substring(begin);
            fastDFSUtil.deleteFile(deleteUrl);
        } catch (NullPointerException e) {
        }
        userService.delPhoto(userId);
        return new Result(true, StatusCode.OK, "删除成功");
    }

    /**
     * 修改自己信息
     *
     * @param user
     */
    @ApiOperation("管理员修改自己接口")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "管理员ID", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "body", name = "user", value = "{\n" +
                    "  \"email\": \"1234@163.com\",\n" +
                    "  \"loginId\": \"123456\",\n" +
                    "  \"mobile\": \"13513513513\",\n" +
                    "  \"name\": \"张三\",\n" +
                    "  \"password\": \"123456\",\n" +
                    "  \"phone\": \"123456789\",\n" +
                    "  \"sex\": \"男\"\n" +
                    "}", required = true, dataType = "User")
    })
    @RequestMapping(value = "/self/{id}", method = RequestMethod.PUT)
    public Result update(@RequestBody User user, @PathVariable String id) {
        UserDetailsImpl userDetails = SecurityContextUtil.getUserDetails();
        if (!emailService.checkEmailRegisted(user.getEmail())){
            return new Result(false,StatusCode.ERROR,"邮箱已被使用");
        }
        if (!id.equals(userDetails.getUserId())) {
            return new Result(false, StatusCode.ERROR, "只能修改自己的信息");
        }
        user.setUserId(id);
        userService.updateUser(user, 1);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    @ApiOperation(value = "管理员获取基地信息")
    @PreAuthorize("hasAnyAuthority('authority')")
    @RequestMapping(value = "/getBase", method = RequestMethod.GET)
    public Result getBase(String userId) {
        HashMap<String, String> base = userService.getBase(userId);
        if (base == null || "".equals(base)) {
            return new Result(false, StatusCode.ERROR, "用户基地信息为空");
        } else {
            return new Result(true, StatusCode.OK, "查询成功", base);
        }
    }

    @ApiOperation(value = "管理员获取店铺信息")
    @PreAuthorize("hasAnyAuthority('authority')")
    @RequestMapping(value = "/getMerchant", method = RequestMethod.GET)
    public Result getMerchant(String userId) {
        HashMap<String,String> map = userService.getMerchant(userId);
        if (map == null || "".equals(userId)) {
            return new Result(false, StatusCode.ERROR, "用户店铺信息为空");
        } else {
            return new Result(true, StatusCode.OK, "查询成功", map);
        }
    }

    @ApiOperation(value = "获取所有的基地信息")
    @PreAuthorize("hasAnyAuthority('enterprise')")
    @RequestMapping(value = "/getAllBase", method = RequestMethod.GET)
    public Result getAllBase() {
        return traceabilityClient.getAllBase();
    }

    @ApiOperation(value = "管理员新增基地")
    @PreAuthorize("hasAnyAuthority('enterprise_enterprise_add')")
    @Transactional
    @ApiImplicitParam(paramType = "body", name = "Base", value = "{\n" +
            "\t\t\"baseName\": \"123456\",\n" +
            "\t\t\t\t\"registNumber\": \"string\"\n" +
            "\t}", required = true, dataType = "Base")
    @RequestMapping(value = "/base", method = RequestMethod.PUT)
    public Result addBaseByAdmin(@RequestBody Base base) {
        UserDetailsImpl user = SecurityContextUtil.getUserDetails();
        base.setCreateBy(user.getName());
        String baseId = idWorker.nextId() + "";
        base.setId(baseId);
        return traceabilityClient.addBase(base);
    }

    @ApiOperation(value = "删除基地")
    @PreAuthorize("hasAnyAuthority('enterprise_enterprise_delete')")
    @RequestMapping(value = "/base/{baseId}", method = RequestMethod.DELETE)
    public Result delBase(@PathVariable String baseId){
        return userService.delBase(baseId);
    }

    @ApiOperation(value = "根据基地ID查询用户")
    @RequestMapping(value = "/user/{baseId}",method = RequestMethod.GET)
    public Result getUserByBaseId(@PathVariable String baseId){
        ArrayList<User> users = null;
        try{
            users = userService.getUserByBaseId(baseId);
        }catch (Exception e){
            throw new GlobalException(new Result(false, StatusCode.ERROR, "获取用户信息失败,"+e.getMessage()));
        }
        return new Result(true, StatusCode.OK,"获取用户成功",users);
    }
}